import { Context } from 'koa'
import { fileService } from '../services/file'

export class FileController {
  // 上传文件
  async upload(ctx: Context) {
    try {
      const files = ctx.request.files
      const userId = ctx.state.user?.id || null
      const fileDataList = await fileService.handleUpload(files, userId)

      ctx.status = 201
      ctx.body = {
        success: true,
        data: fileDataList,
        message: '文件上传成功'
      }
    } catch (error) {
      throw error
    }
  }

  // 删除文件记录及物理文件
  async delete(ctx: Context) {
    try {
      const { id } = ctx.params
      await fileService.delete(parseInt(id))

      ctx.status = 200
      ctx.body = {
        success: true,
        message: '文件删除成功'
      }
    } catch (error) {
      throw error
    }
  }

  // 批量删除文件
  async deleteMultiple(ctx: Context) {
    try {
      const { ids } = ctx.request.body
      console.log('🚀 ~ FileController ~ deleteMultiple ~ ids:', ids)

      if (!ids || !Array.isArray(ids) || ids.length === 0) {
        ctx.status = 400
        ctx.body = {
          success: false,
          message: '请提供有效的文件ID数组'
        }
        return
      }

      await fileService.deleteMultiple(ids)
      ctx.status = 200
      ctx.body = {
        success: true,
        message: '文件批量删除成功'
      }
    } catch (error) {
      throw error
    }
  }

  // 查询所有文件记录
  async findAll(ctx: Context) {
    try {
      const files = await fileService.findAll(ctx.query)
      ctx.status = 200
      ctx.body = {
        success: true,
        data: files,
        message: '查询成功'
      }
    } catch (error) {
      throw error
    }
  }

  // 查询单个文件记录
  async findOne(ctx: Context) {
    try {
      const { id } = ctx.params
      const file = await fileService.findOne(parseInt(id))
      ctx.status = 200
      ctx.body = {
        success: true,
        data: file,
        message: '查询成功'
      }
    } catch (error) {
      throw error
    }
  }
}

export const fileController = new FileController()
